package com.ai.platform.report;

import com.ai.platform.business.entity.BusiDbInfo;
import com.ai.platform.business.mapper.BusiDbInfoMapper;
import com.ai.platform.common.enums.ReportPullTypeEnums;
import com.ai.platform.common.page.PageContext;
import com.ai.platform.common.page.Pagination;
import com.ai.platform.common.util.JDBCUtil;
import com.ai.platform.model.dto.Output;
import com.ai.platform.util.Db;
import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.dubbo.common.json.ParseException;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 功能描述 分页表格数据拉取
 * 创建者 yeyingsheng
 * 创建时间 2018年06月16日
 */
public class TableDataHandle implements IDataHandle{

    private int limit;
    private int pageNow;
    private Map<String,Object> map;

    public TableDataHandle(int limit, int pageNow, Map<String, Object> map) {
        this.limit = limit;
        this.pageNow = pageNow;
        this.map = map;
    }

    @Override
    public void pullData(Output output) {
        String pullType= MapUtils.getString(map,"pullType");
        if(ReportPullTypeEnums.SQL.getId().equals(pullType)){
            PageContext pageContext=PageContext.createPage();
            pageContext.setPageNow(pageNow);
            pageContext.setPageSize(limit);
            //取得参数
            String params=MapUtils.getString(map,"params");
            List<String> paramsList=null;
            if(StringUtils.isNotBlank(params)){
                try {
                    paramsList= JSON.parse(params,List.class);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            try {
                String sqlText=MapUtils.getString(map,"reportHandle");
                String dbId=MapUtils.getString(map,"dbId");
                BusiDbInfo busiDbInfo=Db.create(BusiDbInfoMapper.class).selectOneByCondition("db_id",dbId);
                JDBCUtil db=new JDBCUtil(busiDbInfo.getDriverClassName()
                        ,busiDbInfo.getUrl(),busiDbInfo.getUsername(),busiDbInfo.getPassword());
                Pagination page = db.executeQueryByPage(sqlText, paramsList);
                output.setCount(page.getTotalRows());
                output.setData(page.getData());
            }finally {
                PageContext.removeContext();
            }
        }else if(ReportPullTypeEnums.CLAZZ.getId().equals(pullType)){

        }else if(ReportPullTypeEnums.EXCEL.getId().equals(pullType)){

        }
    }
}
